package com.opencee.common.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * @author yadu
 */
public class DefaultModifyRequestFilter implements Filter {
    public static final String X_REQUEST_ID = "X-Request-Id";
    public static final String TRACE_ID = "traceId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        DefaultServletRequestWrapper requestWrapper = new DefaultServletRequestWrapper(req);
        String traceId = requestWrapper.getHeader(X_REQUEST_ID);
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.randomUUID().toString();
            requestWrapper.putHeader(X_REQUEST_ID, traceId);
        }
        MDC.put(TRACE_ID, traceId);
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {

    }


}
